SOLID- The Single Responsibility Principle in Javascript




SOLID is one of the popular designing pattern. The application that is created using the SOLID principles in object-oriented programming will be easy to maintain.

SOLID stands for

  • Single-Responsibility Principle
  • Open-Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

In this article, we will be focusing on Single-responsibility principle.

What is Single-Responsibility Principle?

A class should have only one responsibility, which in turns makes the class available for modification only for a single reason, since its responsible for performing a single job.If a class has more than one responsibilities then it becomes coupled which is not a good a practise in software development.

Let's see it with an example.

Here, I have a class named Employee which takes 'name' as a parameter in its constructor. It has 2 functions

getEmployeeInfo() - To get the employee name.

saveEmployee() - To save the employee details received from its parameter.

Now the Employee class has two responsibilities, One is to get the employee name and the other is to save the employee details. This form of designing the class will break the Single-responsibility principle. To correct this code we have to break the class into two classes each with one responsibility.

Let's change the code as below

Now Employee class returns the name of the employee and EmployeeDB will do DB related activities.

Having single responsibility for a class can be also extended to a function. A function should also be responsible for a single job.

Let's see it with an example.

Here, we have created a class named Logger. This class has the responsibility to log the message to the console. But when we look into the function it is responsible for forming the message and then logging it to the console. Assume that instead of logging to console you are going to save it to the database. Now the log() function is responsible for performing 2 jobs. Let's change the code as

Now, the class has 3 functions,

formatMessage() - To form the result message.

saveToDB() - To log the result message.

log() - This function is used to log the message by co-ordinating with the other two function to complete the job.

In this scenario, we need a coordinating function, which co-ordinates with other functions and completes the job. But this code just breaks the Open-closed principle. We shall change this code in another article about the Open-closed principle.


Most Read